package cn.smile.business.core.impl;

import cn.smile.bean.dto.core.SysNotPermissionDTO;
import cn.smile.bean.entity.core.SysNotPermission;
import cn.smile.business.core.ISysNotPermissionService;
import cn.smile.commons.constant.RedisKeyConstant;
import cn.smile.commons.domain.BaseServiceImpl;
import cn.smile.repository.core.SysNotPermissionMapper;
import cn.smile.utils.BeanCopy;
import cn.smile.utils.RedisUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import jakarta.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 不需要鉴权的URL 服务实现类
 * </p>
 *
 * @author 龙逸
 * @since 2021-11-28
 */
@Slf4j
@Service
public class SysNotPermissionServiceImpl extends BaseServiceImpl<SysNotPermissionMapper, SysNotPermission> implements ISysNotPermissionService {
    @Resource
    private RedisUtil redisUtil;

    @Override
    public List<SysNotPermissionDTO> getUrlList() {
        log.info("[SysNotPermissionServiceImpl].[getUrlList] ------> System Get Not Permission Url List Start");
        List<SysNotPermission> sysNotPermissions = baseMapper.selectList(new QueryWrapper<SysNotPermission>().lambda().eq(SysNotPermission::getDeleted, false));
        List<SysNotPermissionDTO> resultList = BeanCopy.copyList(sysNotPermissions, SysNotPermissionDTO.class);
        log.info("[SysNotPermissionServiceImpl].[getUrlList] ------> System Get Not Permission Url List End, resultList.size = {}", resultList.size());
        return resultList;
    }

    @Override
    public void writeToRedis() {
        log.info("[SysNotPermissionServiceImpl].[getUrlList] ------> Write Not Permission Url List To Redis Start");
        //根据数据库获取免除权限url
        List<SysNotPermissionDTO> uriList = this.getUrlList();
        if (!CollectionUtils.isEmpty(uriList)) {
            List<String> cacheUris = Lists.newArrayList();
            uriList.forEach(dto -> cacheUris.add(dto.getUrlPath()));
            redisUtil.set(RedisKeyConstant.IGNORE_URLS_KEY, JSON.toJSONString(cacheUris), RedisKeyConstant.IGNORE_URLS_TIMEOUT);
        }
        log.info("[SysNotPermissionServiceImpl].[getUrlList] ------> Write Not Permission Url List To Redis End");
    }
}
